package com.qianyanglong.zhibo.client.panel;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import javax.swing.JPanel;
import org.opencv.core.Mat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CapturePanel extends JPanel{

	private static final long serialVersionUID = -5836639164827844189L;
	
	private static final Logger logger = LoggerFactory.getLogger(CapturePanel.class);

	private Map<String,BufferedImage> map;
	
	private BufferedImage image;
	
	public CapturePanel(Map<String,BufferedImage> map) {
		this.map = map;
	}
	
	public BufferedImage mat2Image(Mat mat) {
		logger.debug("生成图形服务被调用");
		int bufferSize = (int)(mat.rows()*mat.cols()*mat.elemSize());
		byte[] data = new byte[bufferSize];
		mat.get(0, 0, data);
		int channels = mat.channels();
		int type = channels==1?BufferedImage.TYPE_BYTE_GRAY:BufferedImage.TYPE_3BYTE_BGR;
		if(type==BufferedImage.TYPE_3BYTE_BGR) {
			for(int i = 0; i < bufferSize; i+=3) {
				byte blue = data[i];
				data[i] = data[i+2];
				data[i+2] = blue;
			}
		}
		BufferedImage image = new BufferedImage(mat.cols(), mat.rows(), type);
		image.getRaster().setDataElements(0, 0,mat.cols(), mat.rows(), data);
		logger.debug("生成图形服务调用完毕");
		return image;
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		//logger.info("图形数据2:{}",image);
		if(image==null) {
			g.drawOval(0, 0, 500, 500);
			g.dispose();
			return;
		}
		g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
		g.dispose();
	}
	
	public void image(BufferedImage image) {
		this.image = image;
	}

}
